<script lang="ts" setup>
import { ref, reactive, watch } from 'vue';
import { mStyles } from '@/utils/useStyles';

// 定义接口
interface FormField {
  id: number;
  part_name: string;
  part_key: string;
  part_type: 1 | 2 | 3; // 1:单行文本, 2:多行文本, 3:图片上传
  is_require: 0 | 1;   // 0:非必填, 1:必填
  tips_content: string;
  max_num: number;
}

// Props 只需要 formConfig
const props = defineProps<{
  formConfig: FormField[];
  mStyles?: any;
}>();

function deepClone(obj: any) {
  return JSON.parse(JSON.stringify(obj));
}

// 本地表单数据
const localFormData = ref<Record<string, any>>({});

// 初始化图片字段
watch(
  () => props.formConfig,
  (newConfig) => {
    newConfig.forEach(field => {
      if (field.part_type === 3 &&
        (localFormData.value[field.part_key] === undefined ||
          !Array.isArray(localFormData.value[field.part_key]))) {
        localFormData.value[field.part_key] = [];
      }
    });
  },
  { immediate: true, deep: true }
);

// 错误信息
const errors = reactive<Record<string, string>>({});

// 更新本地字段
const updateField = (key: string, value: any) => {
  localFormData.value[key] = value;
};

// 验证单个字段
const validateField = (field: FormField): boolean => {
  const value = localFormData.value[field.part_key];
  if (field.is_require === 1) {
    if (!value || (field.part_type === 3 && Array.isArray(value) && value.length === 0)) {
      errors[field.part_key] = field.part_type === 3
        ? `${field.part_name}至少上传一张图片`
        : `${field.part_name}不能为空`;
      //showToast(errors[field.part_key]);
      return false;
    }
  }
  errors[field.part_key] = '';
  return true;
};

// 整体表单验证
const validate = (): boolean => {
  let isValid = true;
  props.formConfig.forEach(field => {
    if (!validateField(field)) {
      isValid = false;
    }
  });
  return isValid;
};

// 暴露方法给父组件：获取数据和校验
defineExpose({
  validate,
  getFormData: () => deepClone(localFormData.value)
});

</script>

<template>
  <div class="dynamic-form">
    <div v-for="field in formConfig" :key="field.id" class="form-item">
      <div class="gr-input">
        <label class="form-label p-b-[20px]">
          <span v-if="field.is_require" class="required m-r-[5px]">*</span>
          <span class="text-[30px]">{{ field.part_name }}</span>
          <span v-if="field.tips_content">({{ field.tips_content }})</span>
          <span v-if="field.part_type === 3" class="text-[24px] text-[#3D3D3D]/60 float-right">{{ localFormData[field.part_key].length }}/{{ field.max_num }}</span>
        </label>

        <!-- 单行文本 -->
        <cVanfield v-if="field.part_type === 1" :model-value="localFormData[field.part_key]" clearable
          @update:model-value="(val: any) => { updateField(field.part_key, val) }"
          :placeholder="field.tips_content || `请输入${field.part_name}`" @blur="() => { validateField(field); }"
          iBgColor="#FFFFFF" />

        <!-- 多行文本 -->
        <cVanfield v-else-if="field.part_type === 2" :model-value="localFormData[field.part_key]" clearable
          @update:model-value="(val: any) => { updateField(field.part_key, val) }" type="textarea"
          :placeholder="field.tips_content || `请输入${field.part_name}`" :rows="4" iBgColor="#FFFFFF"
          @blur="() => { validateField(field); }" />

        <!-- 图片上传 -->
        <div v-else-if="field.part_type === 3" class="gr-image-upload">
          <cUploadImg v-model="localFormData[field.part_key]" :max="field.max_num" 
            :mStyles="mStyles" />
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
:deep(.van-cell__value){
    font-size:26px;
    color:#3D3D3D;
}
.dynamic-form {
  border-radius: 0 0 10px 10px;
  .gr-input{
    border-radius: 24px;
    padding:30px 20px 30px 20px;
    margin-bottom:20px;
    background:#FFFFFF;
    position: relative;
    :deep(.van-field__word-limit){
        font-size:24px;
        color:rgba(61, 61, 61, 0.6);
        position: absolute;
        top:-70px;
        right:0;
        z-index:99999999;
    }
}
  .form-item {
    margin-bottom: 20px;
  }

  .form-label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    font-size:30px;
    .required {
      color: #ff4d4f;
      margin-left: 4px;
    }
  }

  .error-message {
    color: #ff4d4f;
    font-size: 12px;
    margin-top: 4px;
  }
}
:deep(.van-cell){
    padding:0 0 0 10px;
    overflow: visible;
}
</style>